package com.glory.brepda.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.TextView;

import com.glory.brepda.activity.MainActivity;
import com.glory.brepda.activity.mfg.EqpIDLETypeActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.callback.RequestCallBack;
import com.glory.brepda.entity.ConnectivityManagerEntity;
import com.glory.brepda.entity.request.BaseRequest;
import com.glory.brepda.entity.request.HeaderBean;
import com.glory.brepda.entity.request.RequestBean;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_JsonUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


/**
 * @author yi.zhang
 * @date 2019/6/10
 * @desc 网络请求类
 */
public class NetUtils {

    public static <T> void requestPostNet(String messageName, String method,Object tag, JsonObject jsonString,FreeUI_EntityCallBack<T> callBack){
        RequestBean requestBean = new RequestBean();
        requestBean.setHeader(new HeaderBean(messageName));
        requestBean.setBody(jsonString);
        BaseRequest request = new BaseRequest();
        request.setRequest(requestBean);

        Map<String,String> map = new HashMap<>();

//        map.put("senderId","EAP2CPCSender");
        map.put("requestMessage",StringEscapeUtils.unescapeJson(new Gson().toJson(request)));
        map.put("timeOut","15000");
        Log.e("requestData", "requestData: " + map);
//        FreeApi_LogUtils.saveErrorMessages(StringEscapeUtils.unescapeJson(new Gson().toJson(map)),"请求json");
        FreeApi_LogUtils.saveErrorMessages("http://"+Constant.REQUEST_URL_DEBUG+"/api/"+method,"请求地址");
        Context context = (Context)tag;

        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String wifissid = "";
        String wifiIp = "";
        String mac = "";
        String linkspeed = "";
        if (info != null && info.getMacAddress() != null){
            wifissid = info.getSSID();
            wifiIp = intToIp(info.getIpAddress());
            mac = info.getMacAddress();
            linkspeed = String.valueOf(info.getLinkSpeed());
        }
        ConnectivityManagerEntity c = new ConnectivityManagerEntity();
        c.setSsid(wifissid);
        c.setIp(wifiIp);
        c.setMac(mac);
        c.setLinkspeed(linkspeed);

        FreeApi_LogUtils.saveErrorMessages(StringEscapeUtils.unescapeJson(new Gson().toJson(c)),"网络信息：");
        FreeApi_LogUtils.saveErrorMessages(map.toString(),"请求json");

        FreeApi_NetUtils.requestPostNet("http://"+Constant.REQUEST_URL_DEBUG+"/api/"+method, tag, map, callBack);
//        FreeApi_NetUtils.requestPostNet( Constant.REQUEST_URL_DEBUG + "/esbrest/RestService/postrequest", tag, map, callBack);

//         ((PostRequest) OkGo.post(Constant.REQUEST_URL_DEBUG).tag(tag))
//                .upJson(StringEscapeUtils.unescapeJson(new Gson().toJson(requestMessage))).execute(callBack);
//        OkHttpClient okHttpClient = OkGo.getInstance().getOkHttpClient();
//        OkHttpClient.Builder builder = okHttpClient.newBuilder();
//        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
//        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
//        loggingInterceptor.setColorLevel(Level.INFO);
//        builder.addInterceptor(loggingInterceptor);
//
//        builder.readTimeout(1000L*10,TimeUnit.MILLISECONDS);
//        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
//        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
//
//        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
//        builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
//        builder.hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier);
//        okHttpClient = builder.build();
//        OkGo.getInstance().setOkHttpClient(okHttpClient);
//        ((PostRequest)((PostRequest)OkGo.post("http://"+Constant.REQUEST_URL_DEBUG+"/api/"+method).tag(tag)).params(map, new boolean[]{true})).execute(callBack);

    }

    public static <T> void requestMESPostNet(String messageName, String method,Object tag, JsonObject jsonString,FreeUI_EntityCallBack<T> callBack) {
        RequestBean requestBean = new RequestBean();
        requestBean.setHeader(new HeaderBean(messageName,"EAP"));
        requestBean.setBody(jsonString);
        BaseRequest request = new BaseRequest();
        request.setRequest(requestBean);
//        BaseRequestMessage requestMessage = new BaseRequestMessage();
//        requestMessage.setRequestMessage(request);
        Map<String,String> map = new HashMap<>();
////        map.put("senderId","EAP2CPCSender");
        map.put("requestMessage",StringEscapeUtils.unescapeJson(new Gson().toJson(request)));
//        Log.e("requestData", "requestData: " + StringEscapeUtils.unescapeJson(new Gson().toJson(map)));
        Log.e("requestData", "requestData: " + map);
        FreeApi_LogUtils.saveErrorMessages(map.toString(),"MES提交JSON");
        FreeApi_NetUtils.requestPostNet( "http://"+Constant.REQUEST_URL_DEBUG+"/api/"+method, tag, map, callBack);

//        ((PostRequest) OkGo.post(Constant.REQUEST_MES).tag(tag))
//                .upJson(StringEscapeUtils.unescapeJson(new Gson().toJson(map))).execute(callBack);

    }

    // 可传参数 可传文件
    public static <T> void requestCpcPpf(String url, Map<String, String> params, Map<String, File> files, RequestCallBack<T> callBack){
        url = "http://"+Constant.REQUEST_URL_DEBUG+"/api/"+url;

        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if(params != null){
            for (String key : params.keySet()) {
                builder.addFormDataPart(key, params.get(key));
            }
        }
        if(files != null){
            for (String key : files.keySet()) {
                builder.addFormDataPart(key,files.get(key).getPath(),
                        RequestBody.create(MediaType.parse("application/octet-stream"),files.get(key)));
            }
        }

        RequestBody body = builder.build();

        Request request = new Request.Builder().url(url).method("POST", body).build();
        client.newCall(request).enqueue(callBack);
    }

    private static String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }

    /**
     *
     */
    public static <T> void canceleqpidle(String eqpid, JsonArray eqplist, Object tag, FreeUI_EntityCallBack<T> callBack) {
        if(!eqplist.toString().contains(eqpid)) {
            HashMap hashMap = new HashMap();
            hashMap.put("EQUIPMENTID", eqpid);
            eqplist.add(new JsonParser().parse(new Gson().toJson(hashMap)).getAsJsonObject());
        }
        String messageName = "IF.BREEQPSTATUSQUERY";
        String method = "BRESTANDBYIDLERECORD";
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",eqpid);
        map.addProperty("ACTION","OUT");
        map.add("EQUIPMENTLIST", eqplist);
        requestPostNet(messageName,method, tag,map,callBack);
    }
}
